<template>
  <div class="menu-list-container">
    <Table
      v-loading="loading"
      :columns="columns"
      :data-source="dataSource"
      :count="0"
      :page-no.sync="query.pageNo"
      :page-size.sync="query.pageSize"
      :request="request"
      :list="list"
      :form-data.sync="formData"
      :button-group="buttonGroup"
      :table-props="tableProps"
    />

    <el-dialog :visible.sync="dialogVisible" title="添加菜单" width="800px">
      <PageForm
        ref="dialogForm"
        :form-data.sync="ruleForm"
        :list="pageList"
        :rules="dialogRules"
        label-position="top"
      />
    </el-dialog>

    <el-dialog :visible.sync="dialogEditVisible" title="编辑菜单" width="800px">
      <PageForm
        ref="dialogEditForm"
        :form-data.sync="ruleForm"
        :list="pageEditList"
        :rules="dialogRules"
        label-position="top"
      />
    </el-dialog>
  </div>
</template>

<script>
import Table from "@/components/Table";
import PageForm from "@/components/PageForm";
import {
  getMenuTreeApi,
  addMenuApi,
  updateMenuApi,
  deleteMenuApi,
  enableMenuApi,
  disableMenuApi,
} from "../../../api/auth/menu";
import { treeToArrayOptimized } from "@/utils/treeToArray";

export default {
  name: "MenuList",
  components: {
    Table,
    PageForm,
  },
  data() {
    return {
      dialogVisible: false,
      dialogEditVisible: false,
      query: {
        pageNo: 1,
        pageSize: 10,
      },
      loading: false,
      dataSource: [],
      count: 0,
      formData: {
        menuName: "",
      },
      ruleForm: {
        menuId: "",
        menuName: "",
        parentId: "",
        icon: "",
        menuType: "",
        perms: "",
        path: "",
        component: "",
        sortNum: "",
      },
    };
  },
  computed: {
    treeArray() {
      if (!this.dataSource || !Array.isArray(this.dataSource)) return [];

      return treeToArrayOptimized(this.dataSource);
    },
    // 表格属性配置，支持树形结构
    tableProps() {
      return {
        rowKey: "menuId",
        defaultExpandAll: true,
        treeProps: { children: "children", hasChildren: "hasChildren" },
      };
    },
    // 搜索表单配置
    list() {
      return [
        {
          list: [
            {
              span: 6,
              prop: "menuName",
              component: "input",
              label:"菜单名称",
              componentProps: {
                placeholder: "请输入菜单名称",
              },
            },
          ],
        },
      ];
    },
    // 表格列配置
    columns() {
      return [
        {
          prop: "menuName",
          label: "菜单名称",
        },
        {
          prop: "icon",
          label: "图标",
          type: "img",
        },
        {
          prop: "menuType",
          label: "菜单类型",
          type: "enum",
          enumName: "menuTypeEnum",
        },
        {
          prop: "perms",
          label: "权限标识",
          componentProps: {
            formatter: (row) => {
              return row.perms || "--";
            },
          },
        },
        {
          prop: "path",
          label: "路由地址",
          componentProps: {
            formatter: (row) => {
              return row.path || "--";
            },
          },
        },
        {
          prop: "component",
          label: "组件路径",
          componentProps: {
            formatter: (row) => {
              return row.component || "--";
            },
          },
        },
        // switch
        {
          prop: "isEnabled",
          label: "状态",
          type: "switch",
          width: 180,
          switchProps: {
            activeValue: "1",
            inactiveValue: "0",
            activeText: "启用",
            inactiveText: "停用",
            onChange: (row) => {
              this.handleStatusChange(row);
            },
          },
        },
        {
          prop: "sortNum",
          label: "排序",
        },
        {
          prop: "action",
          label: "操作",
          type: "action",
          width: 350,
          componentProps: {
            fixed: "right",
          },
          buttonGroup: [
            {
              label: "添加子菜单",
              type: "primary",
              size: "small",
              // statusName: ["menuType"],
              // status: "1",
              click: (row) => {
                this.resetForm();
                this.ruleForm.parentId = row.menuId;
                this.dialogVisible = true;
              },
            },
            {
              label: "编辑",
              type: "primary",
              size: "small",
              click: (row) => {
                this.dialogEditVisible = true;
                this.ruleForm = { ...row };
              },
            },
            {
              label: "删除",
              type: "danger",
              size: "small",
              click: (row) => {
                this.$confirm("此操作将删除此菜单, 是否继续?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }).then(async () => {
                  try {
                    await deleteMenuApi({ menuId: row.menuId });
                    this.$message.success("删除成功");
                    this.request();
                  } catch (error) {
                    this.$message.error("删除失败");
                  }
                });
              },
            },
          ],
        },
      ];
    },
    // 按钮组配置
    buttonGroup() {
      return [
        {
          label: "添加",
          type: "primary",
          click: () => {
            this.resetForm();
            this.ruleForm.parentId = "0";
            this.dialogVisible = true;
          },
        },
      ];
    },
    // 添加表单配置
    pageList() {
      return [
        {
          list: [
            {
              span: 12,
              prop: "parentId",
              label: "父级菜单",
              component: "Treeselect",
              treeSelectList: [
                {
                  menuId: "0",
                  menuName: "主类目",
                  children: this.dataSource || [],
                },
              ],
              normalizer(node) {
                if (node.children && !node.children.length) {
                  delete node.children;
                }
                // 兼容不同的数据结构
                return {
                  id: node.menuId,
                  label: node.menuName,
                  children: node.children,
                };
              },
              componentProps: {
                placeholder: "请选择父级菜单",
              },
            },
            {
              span: 12,
              prop: "menuName",
              label: "菜单名称",
              component: "input",
              componentProps: {
                placeholder: "请输入菜单名称",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 12,
              prop: "menuType",
              label: "菜单类型",
              component: "enum",
              enumName: "menuTypeEnum",
            },
            {
              span: 12,
              prop: "sortNum",
              label: "排序",
              component: "input",
              componentProps: {
                type: "number",
                placeholder: "请输入排序",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 12,
              prop: "perms",
              label: "权限标识",
              component: "input",
              componentProps: {
                placeholder: "请输入权限标识",
              },
            },
            {
              span: 12,
              prop: "path",
              label: "路由地址",
              component: "input",
              componentProps: {
                placeholder: "请输入路由地址",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 12,
              prop: "component",
              label: "组件路径",
              component: "input",
              componentProps: {
                placeholder: "请输入组件路径",
              },
            },
            {
              span: 12,
              prop: "icon",
              label: "图标",
              component: "imgUpload",
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              label: "",
              prop: "action",
              component: "action",
              componentProps: [
                {
                  label: "取消",
                  type: "default",
                  click: () => {
                    this.dialogVisible = false;
                    this.resetForm();
                  },
                },
                {
                  label: "确定",
                  type: "primary",
                  click: () => {
                    if (this.$refs.dialogForm) {
                      this.$refs.dialogForm.validate((valid) => {
                        if (valid) {
                          this.handleSave();
                        }
                      });
                    }
                  },
                },
              ],
            },
          ],
        },
      ];
    },
    // 编辑表单配置
    pageEditList() {
      return [
        {
          list: [
            {
              span: 12,
              prop: "parentId",
              label: "父级菜单",
              component: "Treeselect",
              treeSelectList: [
                {
                  menuId: "0",
                  menuName: "主类目",
                  children: this.dataSource || [],
                },
              ],
              normalizer(node) {
                if (node.children && !node.children.length) {
                  delete node.children;
                }
                // 兼容不同的数据结构
                return {
                  id: node.menuId,
                  label: node.menuName,
                  children: node.children,
                };
              },
              componentProps: {
                placeholder: "请选择父级菜单",
              },
            },
            {
              span: 12,
              prop: "menuName",
              label: "菜单名称",
              component: "input",
              componentProps: {
                placeholder: "请输入菜单名称",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 12,
              prop: "menuType",
              label: "菜单类型",
              component: "enum",
              enumName: "menuTypeEnum",
            },
            {
              span: 12,
              prop: "sortNum",
              label: "排序",
              component: "input",
              componentProps: {
                type: "number",
                placeholder: "请输入排序",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 12,
              prop: "perms",
              label: "权限标识",
              component: "input",
              componentProps: {
                placeholder: "请输入权限标识",
              },
            },
            {
              span: 12,
              prop: "path",
              label: "路由地址",
              component: "input",
              componentProps: {
                placeholder: "请输入路由地址",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 12,
              prop: "component",
              label: "组件路径",
              component: "input",
              componentProps: {
                placeholder: "请输入组件路径",
              },
            },
            {
              span: 12,
              prop: "icon",
              label: "图标",
              component: "imgUpload",
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              label: "",
              prop: "action",
              component: "action",
              componentProps: [
                {
                  label: "取消",
                  type: "default",
                  click: () => {
                    this.dialogEditVisible = false;
                    this.resetForm();
                  },
                },
                {
                  label: "确定",
                  type: "primary",
                  click: () => {
                    if (this.$refs.dialogEditForm) {
                      this.$refs.dialogEditForm.validate((valid) => {
                        if (valid) {
                          this.handleUpdate();
                        }
                      });
                    }
                  },
                },
              ],
            },
          ],
        },
      ];
    },
    // 表单验证规则
    dialogRules() {
      return {
        menuName: [
          { required: true, message: "请输入菜单名称", trigger: "blur" },
        ],
        menuType: [
          { required: true, message: "请选择菜单类型", trigger: "change" },
        ],
        sortNum: [{ required: true, message: "请输入排序", trigger: "blur" }],
      };
    },
  },
  methods: {
    // 请求数据
    async request() {
      try {
        if (this.loading) return;

        this.loading = true;

        const res = await getMenuTreeApi({
          menuName: this.formData.menuName,
        });

        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.dataSource = res.data || [];
        this.count = this.dataSource.length;
      } catch (error) {
        console.log(error);
        this.$message.error("获取菜单列表失败");
      } finally {
        this.loading = false;
      }
    },
    // 处理状态变更
    async handleStatusChange(row) {
      try {
        if (this.loading) return;

        this.loading = true;

        if (row.isEnabled === "1") {
          await enableMenuApi({ menuId: row.menuId });
          this.$message.success("启用成功");
        } else {
          await disableMenuApi({ menuId: row.menuId });
          this.$message.success("停用成功");
        }

        this.loading = false;

        this.request();
      } catch (error) {
        this.loading = false;
        this.$message.error("状态变更失败");
        // 恢复原状态
        row.isEnabled = row.isEnabled === "1" ? "0" : "1";
      }
    },
    // 处理保存
    async handleSave() {
      try {
        if (this.loading) return;
        this.loading = true;

        const res = await addMenuApi(this.ruleForm);

        this.loading = false;

        if (res.code === 200) {
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.resetForm();
          this.request();
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // 处理更新
    async handleUpdate() {
      try {
        if (this.loading) return;
        this.loading = true;

        const res = await updateMenuApi(this.ruleForm);

        this.loading = false;

        if (res.code === 200) {
          this.$message.success("更新成功");
          this.dialogEditVisible = false;
          this.resetForm();
          this.request();
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // 重置表单
    resetForm() {
      this.ruleForm = {
        menuId: "",
        menuName: "",
        parentId: "",
        icon: "",
        menuType: "",
        perms: "",
        path: "",
        component: "",
        sortNum: "",
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.menu-list-container {
  padding: 20px;
}
</style>
